package product;

import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeMap;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;




public class SortType {

	/**统计排名前3 的省份共同拥有的农产品类型
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		if (args.length != 2) {
			System.err.println("path err!");
			System.exit(-1);
		}
		Job job = new Job(new Configuration(), "sortby");
		job.setJarByClass(SortType.class);

		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));

		job.setMapperClass(sortMaps.class);
		job.setReducerClass(sortReduce.class);

		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(Text.class);

		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);

		job.waitForCompletion(true);
	}
	public static class sortMaps extends Mapper<LongWritable, Text, Text, Text>{
		protected void map(LongWritable key, Text value, org.apache.hadoop.mapreduce.Mapper<LongWritable,Text,Text,Text>.Context context) throws java.io.IOException ,InterruptedException {
			String[] lines = value.toString().split("\t");
			if (lines.length==6) {
				String type = lines[0].trim();
				String provice = lines[4].trim();
				context.write(new Text(provice), new Text(type));
			}
		};
	}
	public static class sortReduce extends Reducer<Text, Text, Text, Text>{
		private static TreeMap<Integer,String> tm=new TreeMap<>(
				new Comparator<Integer>() {
					@Override
					public int compare(Integer o1, Integer o2) {
						// 降序
						return o2.compareTo(o1);
					}
				}
				);
		
		Set<String> sets=new HashSet<>();
		protected void reduce(Text k2, java.lang.Iterable<Text> values, org.apache.hadoop.mapreduce.Reducer<Text,Text,Text,Text>.Context context) throws java.io.IOException ,InterruptedException {

			for (Text types: values) {
				sets.add(types.toString());
			}
			tm.put(sets.size(),k2.toString()+"-"+sets.toString());
		};
		protected void cleanup(org.apache.hadoop.mapreduce.Reducer<Text,Text,Text,Text>.Context context) throws java.io.IOException ,InterruptedException {
			for (int i = 0; i < tm.size(); i++) {
			
			}
		};
	}
}
